using System;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Globalization;
using System.Collections;
using System.Resources;
using System.Collections.Specialized;

namespace AjaxControlToolkitEx
{
    public class GridViewEx : GridView
    {
        protected override void OnRowDeleting(GridViewDeleteEventArgs e)
        {
            base.OnRowDeleting(e);

            GridView gv = this as GridView;

            ObjectDataSource ods = FindDataSourceControl(gv, gv.DataSourceID) as ObjectDataSource;

            if (ods != null && !string.IsNullOrEmpty(ods.DeleteMethod))
            {
                System.Collections.Generic.Dictionary<object, object> keyMap = new System.Collections.Generic.Dictionary<object, object>();
                System.Collections.Generic.Dictionary<object, object> keyvalue = new System.Collections.Generic.Dictionary<object, object>();
                foreach (DictionaryEntry key in e.Keys)
                {
                    keyvalue.Add(key.Key, key.Value);
                    keyMap.Add(key.Key.ToString().ToLower(), key.Key);
                }
                e.Keys.Clear();

                foreach (Parameter p in ods.DeleteParameters)
                {
                    string keyname = p.Name.ToLower();
                    if (keyMap.ContainsKey(keyname))
                        e.Keys.Add(keyMap[keyname], keyvalue[keyMap[keyname]]);
                }
            }
        }

        private static Control SearchControl(Control pctl, string id)
        {
            Control obj = pctl.FindControl(id);
            if (obj == null)
                foreach (Control ctl in pctl.Controls)
                {
                    obj = SearchControl(ctl, id);
                    if (obj != null)
                        break;
                }

            return obj;
        }
        private static Control SearchControl(Page page, string id)
        {
            Control obj = page.FindControl(id);
            if (obj == null)
                foreach (Control ctl in page.Controls)
                {
                    obj = SearchControl(ctl, id);
                    if (obj != null)
                        break;
                }

            return obj;
        }

        private static Control FindDataSourceControl(Control control, string controlID)
        {
            Control namingContainer = control;
            Control control3 = null;
            if (control != control.Page)
            {
                while ((control3 == null) && (namingContainer != control.Page))
                {
                    namingContainer = namingContainer.NamingContainer;
                    if (namingContainer == null)
                    {
                        return null;
                    }
                    control3 = namingContainer.FindControl(controlID);
                }
                return control3;
            }
            return SearchControl(control, controlID);
        }

        public GridViewRow GetParentRow(Control ctl)
        {
            while (ctl != null)
            {
                if (ctl.Parent != null && ctl.Parent is GridViewRow)
                    return ctl.Parent as GridViewRow;
                ctl = ctl.Parent;
            }
            return null;
        }

    }

    public class Static : Label
    {
        #region Render
        public override void RenderBeginTag(HtmlTextWriter writer)
        {
            string oldID = this.ID;
            this.ID = null;
            this.AddAttributesToRender(writer);
            this.ID = oldID;
            HtmlTextWriterTag tagKey = this.TagKey;
            if (tagKey != HtmlTextWriterTag.Unknown)
            {
                writer.RenderBeginTag(tagKey);
            }
            else
            {
                writer.RenderBeginTag(this.TagName);
            }
        }
        #endregion
    }

    public class LabelEx : Label
    {
        public string ResourceType
        {
            set
            {
                ViewState["ResourceType"] = value;
            }
            private get
            {
                return (string)ViewState["ResourceType"];
            }
        }
        public string ResourceModuleName
        {
            set
            {
                ViewState["ResourceModuleName"] = value;
            }
            private get
            {
                if (ViewState["ResourceModuleName"] == null)
                    ViewState["ResourceModuleName"] = "App_GlobalResources";
                return (string)ViewState["ResourceModuleName"];
            }
        }
        protected string GetResource(string key)
        {
            ResourceManager resMan = new ResourceManager(ResourceType, System.Reflection.Assembly.Load(ResourceModuleName));
            return resMan.GetString(key);
        }
    }


    public class RadioButtonEx : RadioButton
    {
        /*
        private static string EnsureEndWithSemiColon(string value)
        {
            if (value != null)
            {
                int length = value.Length;
                if ((length > 0) && (value[length - 1] != ';'))
                {
                    return (value + ";");
                }
            }
            return value;
        }
        private static string MergeScript(string firstScript, string secondScript)
        {
            if (!string.IsNullOrEmpty(firstScript))
            {
                return (firstScript + secondScript);
            }
            if (secondScript.TrimStart(new char[0]).StartsWith("javascript:", StringComparison.Ordinal))
            {
                return secondScript;
            }
            return ("javascript:" + secondScript);
        }
        protected override void Render(HtmlTextWriter writer)
        {
            this.AddAttributesToRender(writer);
            if (this.Page != null)
            {
                this.Page.VerifyRenderingInServerForm(this);
            }
            bool flag = false;
            if (base.ControlStyleCreated)
            {
                Style controlStyle = base.ControlStyle;
                if (!controlStyle.IsEmpty)
                {
                    controlStyle.AddAttributesToRender(writer, this);
                    flag = true;
                }
            }
            if (!base.IsEnabled)
            {
                writer.AddAttribute(HtmlTextWriterAttribute.Disabled, "disabled");
                flag = true;
            }
            string toolTip = this.ToolTip;
            if (toolTip.Length > 0)
            {
                writer.AddAttribute(HtmlTextWriterAttribute.Title, toolTip);
                flag = true;
            }
            string str2 = null;
            if (base.HasAttributes)
            {
                System.Web.UI.AttributeCollection attributes = base.Attributes;
                string str3 = attributes["value"];
                if (str3 != null)
                {
                    attributes.Remove("value");
                }
                str2 = attributes["onclick"];
                if (str2 != null)
                {
                    str2 = EnsureEndWithSemiColon(str2);
                    attributes.Remove("onclick");
                }
                //str2 += string.Format("this.value = this.checked; alert(this.value);");
                if (attributes.Count != 0)
                {
                    attributes.AddAttributes(writer);
                    flag = true;
                }
                if (str3 != null)
                {
                    attributes["value"] = str3;
                }
            }
            if (flag)
            {
                writer.RenderBeginTag(HtmlTextWriterTag.Span);
            }
            string text = this.Text;
            string clientID = this.ClientID;
            if (text.Length != 0)
            {
                if (this.TextAlign == TextAlign.Left)
                {
                    this.RenderLabel(writer, text, clientID);
                    this.RenderInputTag(writer, clientID, str2);
                }
                else
                {
                    this.RenderInputTag(writer, clientID, str2);
                    this.RenderLabel(writer, text, clientID);
                }
            }
            else
            {
                this.RenderInputTag(writer, clientID, str2);
            }
            if (flag)
            {
                writer.RenderEndTag();
            }
        }
        protected override bool LoadPostData(string postDataKey, NameValueCollection postCollection)
        {
            string eventArgument = postCollection[this.GroupName];
            bool flag = false;
            if ((eventArgument != null) && ClientID.Equals(postDataKey))
            {

                this.Checked = (eventArgument == ClientID);
                flag = true;

                return flag;
            }
            return flag;
        }
        private void RenderInputTag(HtmlTextWriter writer, string clientID, string onClick)
        {
            writer.AddAttribute(HtmlTextWriterAttribute.Id, clientID);
            writer.AddAttribute(HtmlTextWriterAttribute.Type, "radio");
            writer.AddAttribute(HtmlTextWriterAttribute.Name, this.GroupName);
            writer.AddAttribute(HtmlTextWriterAttribute.Value, this.ClientID);
            //if (this.Page != null)
            //{
            //this.Page.ClientScript.RegisterForEventValidation(this.GroupName, this.ValueAttribute);
            //}
            if (this.Checked)
            {
                writer.AddAttribute(HtmlTextWriterAttribute.Checked, "checked");
            }
            if (!base.IsEnabled)
            {
                writer.AddAttribute(HtmlTextWriterAttribute.Disabled, "disabled");
            }
            if ((this.AutoPostBack && !this.Checked) && (this.Page != null))
            {
                PostBackOptions options = new PostBackOptions(this, string.Empty);
                if (this.CausesValidation)
                {
                    options.PerformValidation = true;
                    options.ValidationGroup = this.ValidationGroup;
                }
                if (this.Page.Form != null)
                {
                    options.AutoPostBack = true;
                }
                onClick = MergeScript(onClick, this.Page.ClientScript.GetPostBackEventReference(options));
                writer.AddAttribute(HtmlTextWriterAttribute.Onclick, onClick);
            }
            else if (onClick != null)
            {
                writer.AddAttribute(HtmlTextWriterAttribute.Onclick, onClick);
            }
            string accessKey = this.AccessKey;
            if (accessKey.Length > 0)
            {
                writer.AddAttribute(HtmlTextWriterAttribute.Accesskey, accessKey);
            }
            int tabIndex = this.TabIndex;
            if (tabIndex != 0)
            {
                writer.AddAttribute(HtmlTextWriterAttribute.Tabindex, tabIndex.ToString(NumberFormatInfo.InvariantInfo));
            }
            if ((base.InputAttributes != null) && (base.InputAttributes.Count != 0))
            {
                base.InputAttributes.AddAttributes(writer);
            }
            writer.RenderBeginTag(HtmlTextWriterTag.Input);
            writer.RenderEndTag();
        }

        private void RenderLabel(HtmlTextWriter writer, string text, string clientID)
        {
            writer.AddAttribute(HtmlTextWriterAttribute.For, clientID);
            if ((this.LabelAttributes != null) && (this.LabelAttributes.Count != 0))
            {
                this.LabelAttributes.AddAttributes(writer);
            }
            writer.RenderBeginTag(HtmlTextWriterTag.Label);
            writer.Write(text);
            writer.RenderEndTag();
        }
        */
    }

    public class StaticCheckBoxField : CheckBoxField
    {
        #region Init
        public string HeaderToolTip
        {
            get
            {
                object obj2 = this.ViewState["HeaderToolTip"];
                if (obj2 != null)
                {
                    return (string)obj2;
                }
                return string.Empty;
            }
            set
            {
                if (!object.Equals(value, this.ViewState["HeaderToolTip"]))
                {
                    this.ViewState["HeaderToolTip"] = value;
                    this.OnFieldChanged();
                }
            }
        }
        public override void InitializeCell(DataControlFieldCell cell, DataControlCellType cellType, DataControlRowState rowState, int rowIndex)
        {
            base.InitializeCell(cell, cellType, rowState, rowIndex);
            if (cellType == DataControlCellType.Header)
            {
                cell.ToolTip = HeaderToolTip;
            }
        }
        protected override void InitializeDataCell(DataControlFieldCell cell, DataControlRowState rowState)
        {
            CheckBox child = null;
            CheckBox box2 = null;
            if (this.DataField.Length != 0)
            {
                CheckBox box4 = new ReadOnlyCheckBox();
                box4.ToolTip = HeaderToolTip;
                box4.Text = this.Text;
                box4.Enabled = false;
                child = box4;
                box2 = box4;
            }
            if (child != null)
            {
                cell.Controls.Add(child);
            }
            if ((box2 != null) && base.Visible)
            {
                box2.DataBinding += new EventHandler(this.OnDataBindField);
            }
        }
        #region Private
        internal class ReadOnlyCheckBox : CheckBox
        {
            #region Render
            protected override void Render(HtmlTextWriter writer)
            {
                this.AddAttributesToRender(writer);
                if (this.Page != null)
                {
                    this.Page.VerifyRenderingInServerForm(this);
                }
                bool flag = false;
                if (base.ControlStyleCreated)
                {
                    Style controlStyle = base.ControlStyle;
                    if (!controlStyle.IsEmpty)
                    {
                        controlStyle.AddAttributesToRender(writer, this);
                        flag = true;
                    }
                }
                {
                    writer.AddAttribute(HtmlTextWriterAttribute.Disabled, "disabled");
                    flag = true;
                }
                string toolTip = this.ToolTip;
                if (toolTip.Length > 0)
                {
                    writer.AddAttribute(HtmlTextWriterAttribute.Title, toolTip);
                    flag = true;
                }
                string str2 = null;
                if (flag)
                {
                    writer.RenderBeginTag(HtmlTextWriterTag.Span);
                }
                string text = this.Text;
                if (text.Length != 0)
                {
                    if (this.TextAlign == TextAlign.Left)
                    {
                        this.StaticRenderLabel(writer, text);
                        this.StaticRenderInputTag(writer, str2);
                    }
                    else
                    {
                        this.StaticRenderInputTag(writer, str2);
                        this.StaticRenderLabel(writer, text);
                    }
                }
                else
                {
                    this.StaticRenderInputTag(writer, str2);
                }
                if (flag)
                {
                    writer.RenderEndTag();
                }
            }
            private void StaticRenderInputTag(HtmlTextWriter writer, string onClick)
            {
                writer.AddAttribute(HtmlTextWriterAttribute.Type, "checkbox");
                if (this.Checked)
                {
                    writer.AddAttribute(HtmlTextWriterAttribute.Checked, "checked");
                }
                if (!base.IsEnabled)
                {
                    writer.AddAttribute(HtmlTextWriterAttribute.Disabled, "disabled");
                }
                string accessKey = this.AccessKey;
                if (accessKey.Length > 0)
                {
                    writer.AddAttribute(HtmlTextWriterAttribute.Accesskey, accessKey);
                }
                int tabIndex = this.TabIndex;
                if (tabIndex != 0)
                {
                    writer.AddAttribute(HtmlTextWriterAttribute.Tabindex, tabIndex.ToString(System.Globalization.NumberFormatInfo.InvariantInfo));
                }
                writer.RenderBeginTag(HtmlTextWriterTag.Input);
                writer.RenderEndTag();
            }
            private void StaticRenderLabel(HtmlTextWriter writer, string text)
            {
                writer.RenderBeginTag(HtmlTextWriterTag.Label);
                writer.Write(text);
                writer.RenderEndTag();
            }
            #endregion
        }
        #endregion
        #endregion
    }

    public class MultiLineBoundField : BoundFieldEx
    {
        #region Init
        protected override void OnDataBindField(object sender, EventArgs e)
        {
            Control control = (Control)sender;
            Control namingContainer = control.NamingContainer;
            object dataValue = this.GetValue(namingContainer);
            bool encode = (this.SupportsHtmlEncode && this.HtmlEncode) && (control is TableCell);
            string str = this.FormatDataValue(dataValue, encode);
            if (control is TableCell)
            {
                str = str.Replace("\n", "<br/>");
                if (str.Length == 0)
                {
                    str = "&nbsp;";
                }
                ((TableCell)control).Text = str;
            }
        }

        protected override void InitializeDataCell(DataControlFieldCell cell, DataControlRowState rowState)
        {
            Control control2 = null;
            if (this.DataField.Length != 0)
            {
                control2 = cell;
            }
            if ((control2 != null) && base.Visible)
            {
                control2.DataBinding += new EventHandler(this.OnDataBindField);
            }
        }
        #endregion
    }

    public class PercentageBoundField : BoundFieldEx
    {
        #region Init
        protected override void OnDataBindField(object sender, EventArgs e)
        {
            Control control = (Control)sender;
            Control namingContainer = control.NamingContainer;
            object dataValue = this.GetValue(namingContainer);
            decimal decimalValue = 0;
            if (Decimal.TryParse(dataValue.ToString(), out decimalValue))
            {
                dataValue = decimalValue * 100;
            }
            bool encode = (this.SupportsHtmlEncode && this.HtmlEncode) && (control is TableCell);
            string str = this.FormatDataValue(dataValue, encode);
            if (control is TableCell)
            {
                if (str.Length == 0)
                {
                    str = "&nbsp;";
                }
                else
                {
                    str += "%";
                }
                ((TableCell)control).Text = str;
            }
        }

        protected override void InitializeDataCell(DataControlFieldCell cell, DataControlRowState rowState)
        {
            Control control2 = null;
            if (this.DataField.Length != 0)
            {
                control2 = cell;
            }
            if ((control2 != null) && base.Visible)
            {
                control2.DataBinding += new EventHandler(this.OnDataBindField);
            }
        }
        #endregion
    }

    public class DateTimeBoundField : BoundFieldEx
    {
        #region Init
        private string dateFormat;
        public string DateFormat
        {
            get
            {
                return dateFormat;
            }
            set
            {
                dateFormat = value;
            }
        }
        private string timeFormat;
        public string TimeFormat
        {
            get
            {
                return timeFormat;
            }
            set
            {
                timeFormat = value;
            }
        }
        private string dateTimeFormat;
        public string DateTimeFormat
        {
            get
            {
                return dateTimeFormat;
            }
            set
            {
                dateTimeFormat = value;
            }
        }

        protected override void OnDataBindField(object sender, EventArgs e)
        {
            Control control = (Control)sender;
            Control namingContainer = control.NamingContainer;
            object dataValue = this.GetValue(namingContainer);
            bool encode = (this.SupportsHtmlEncode && this.HtmlEncode) && (control is TableCell);
            string str = this.FormatDataValue(dataValue, encode);
            DateTime datetimeValue;
            if (DateTime.TryParse(dataValue.ToString(), out datetimeValue))
            {
                DateTime data = (DateTime)dataValue;
                string format = DateTimeFormat;

                if (data.TimeOfDay.Hours == 0 &&
                        data.TimeOfDay.Minutes == 0 &&
                        data.TimeOfDay.Seconds == 0
                )
                    if (!string.IsNullOrEmpty(DateFormat))
                        format = DateFormat;

                if (!string.IsNullOrEmpty(TimeFormat))
                    format = TimeFormat;

                if (!string.IsNullOrEmpty(format))
                {
                    str = data.ToString(format);
                }
            }
            if (control is TableCell)
            {
                if (str.Length == 0)
                {
                    str = "&nbsp;";
                }
                ((TableCell)control).Text = str;
            }
        }

        protected override void InitializeDataCell(DataControlFieldCell cell, DataControlRowState rowState)
        {
            Control control2 = null;
            if (this.DataField.Length != 0)
            {
                control2 = cell;
            }
            if ((control2 != null) && base.Visible)
            {
                control2.DataBinding += new EventHandler(this.OnDataBindField);
            }
        }
        #endregion
    }

    public class BoundFieldEx : System.Web.UI.WebControls.BoundField
    {
        #region Init
        public string HeaderToolTip
        {
            get
            {
                object obj2 = this.ViewState["HeaderToolTip"];
                if (obj2 != null)
                {
                    return (string)obj2;
                }
                return string.Empty;
            }
            set
            {
                if (!object.Equals(value, this.ViewState["HeaderToolTip"]))
                {
                    this.ViewState["HeaderToolTip"] = value;
                    this.OnFieldChanged();
                }
            }
        }
        public int TruncateLength
        {
            get
            {
                object obj2 = this.ViewState["TruncateLength"];
                if (obj2 != null)
                {
                    return (int)obj2;
                }
                return 0;
            }
            set
            {
                if (!object.Equals(value, this.ViewState["TruncateLength"]))
                {
                    this.ViewState["TruncateLength"] = value;
                    this.OnFieldChanged();
                }
            }
        }

        protected override void OnDataBindField(object sender, EventArgs e)
        {
            Control control = (Control)sender;
            Control namingContainer = control.NamingContainer;
            object dataValue = this.GetValue(namingContainer);
            bool encode = (this.SupportsHtmlEncode && this.HtmlEncode) && (control is TableCell);
            string str = this.FormatDataValue(dataValue, encode);
            if (control is TableCell)
            {
                str = str.Trim();
                if (str.Length > TruncateLength && TruncateLength > 0)
                {
                    str = str.Substring(0, Math.Min(TruncateLength, str.Length)) + "...";
                }
                if (str.Length == 0)
                {
                    str = "&nbsp;";
                }
                ((TableCell)control).Text = str;
            }
        }

        public override void InitializeCell(DataControlFieldCell cell, DataControlCellType cellType, DataControlRowState rowState, int rowIndex)
        {
            base.InitializeCell(cell, cellType, rowState, rowIndex);
            if (cellType == DataControlCellType.Header)
            {
                cell.ToolTip = HeaderToolTip;
            }
        }
        #endregion
    }

    public class ResourceBoundFieldEx : BoundFieldEx
    {
        #region Init
        public string ResourceType
        {
            set
            {
                ViewState["ResourceType"] = value;
            }
            private get
            {
                return (string)ViewState["ResourceType"];
            }
        }
        public string ResourceModuleName
        {
            set
            {
                ViewState["ResourceModuleName"] = value;
            }
            private get
            {
                if (ViewState["ResourceModuleName"] == null)
                    ViewState["ResourceModuleName"] = "App_GlobalResources";
                return (string)ViewState["ResourceModuleName"];
            }
        }
        private string GetResource(string key)
        {
            ResourceManager resMan = new ResourceManager(ResourceType, System.Reflection.Assembly.Load(ResourceModuleName));
            return resMan.GetString(key);
        }
        protected override void OnDataBindField(object sender, EventArgs e)
        {
            Control control = (Control)sender;
            Control namingContainer = control.NamingContainer;
            object dataValue = this.GetValue(namingContainer);
            string str = GetResource(Convert.ToString(dataValue));
            if (control is TableCell)
            {
                str = str.Trim();
                if (str.Length == 0)
                {
                    str = "&nbsp;";
                }
                ((TableCell)control).Text = str;
            }
        }
        #endregion
    }

}
